# -*- coding:utf-8 -*-
"""
@Created on : 2025/01/29 14:27
@Author: xiaomi
@Des: fastapi事件监听
"""

from fastapi import FastAPI
from tortoise import Tortoise
import redis.asyncio as redis
from database.mysql import init_db, close_db

async def startup(app: FastAPI):
    try:
        # Initialize resources
        print("Starting up...")
        # 注册数据库
        await init_db()
        # 注入缓存到app state
        r = redis.Redis(host='127.0.0.1', port=6379, db=0)
        app.state.cache = r

    except Exception as e:
        print(f"Startup failed: {e}")
        raise  # Re-raise to halt the app if critical

async def shutdown(app: FastAPI):
    try:
        # Cleanup resources
        print("Shutting down...")
        await close_db()
        r = app.state.cache
        await r.close()
    except Exception as e:
        print(f"Shutdown error: {e}")
